package com.evon.yardmanagement.export;

import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.evon.yardmanagement.service.SectionManagementService;

/**
 * Class responsible for importing data from excel.
 * 
 * @author vgaurav
 * 
 * @param <T>
 */
public class ImportDataManager<T extends ImportableData> {
	// Wrapping the export able data which has to be exported into excel.
	T exportableData;

	public ImportDataManager(T exportData) {
		this.exportableData = exportData;
	}

	public void importDataFromExcel() {

		try {
			FileInputStream inputStream = new FileInputStream(exportableData
					.getFileToImport());

			/** Create a POIFSFileSystem object **/

			POIFSFileSystem myFileSystem = new POIFSFileSystem(inputStream);

			/** Create a workbook using the File System **/

			HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

			/** Get the first sheet from workbook **/

			HSSFSheet mySheet = myWorkBook.getSheetAt(0);

			System.out.println("mySheet" + mySheet);

			/** We now need something to iterate through the cells. **/

			int totoalRowCount = mySheet.getLastRowNum();

			// Row count starts form 1 as we want to skip header section.
			for (int rowCounter = 1; rowCounter <= totoalRowCount; rowCounter++) {

				HSSFRow myRow = mySheet.getRow(rowCounter);

				int totalColumnCount = myRow.getLastCellNum();
				for (int columnCounter = 0; columnCounter < totalColumnCount; columnCounter++) {

					HSSFCell myCell = myRow.getCell((short) columnCounter);
					if (myCell != null) {
						Object value = null;
						if (HSSFCell.CELL_TYPE_NUMERIC == myCell.getCellType()) {
							value = (int) myCell.getNumericCellValue();
						} else if (HSSFCell.CELL_TYPE_STRING == myCell
								.getCellType()) {
							value = myCell.getStringCellValue();
						}
						if (value != null)
							exportableData.setValueAt(rowCounter - 1,
									columnCounter, value);
					}

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
